class BranchOffice < ActiveRecord::Base
  belongs_to :company
  has_many :holidays
  has_many :users
  has_and_belongs_to_many :departments

  validates_presence_of :name
  validates_presence_of :city
  validates_presence_of :company_id
  validates_uniqueness_of :name, :scope => :company_id
  validates_uniqueness_of :city, :scope => :company_id

  def add_holiday=(list)
    list["reason"].each_index do |i|
      Holiday.create!(:reason => list["reason"][i], :holiday_date => list["date"][i], :branch_office_id => self.id) unless list["date"][i] == 'yyyy-mm-dd'
    end
  end

  def update_holiday=(list)
    list.each do |hid, values|
      if values["reason"].blank? and values["date"].blank?
        Holiday.find(hid).destroy
      else
        Holiday.find(hid).update_attributes! :reason => values["reason"], :holiday_date => values["date"]
      end
    end
  end

  def holiday_days(month=Time.now.month, year=Time.now.year)
    BranchOffice.connection.execute "CALL holiday_days(#{self.id}, #{month}, #{year}, @result)"
    BranchOffice.connection.execute("SELECT @result AS result").fetch_row.first.to_i
  end

  def business_days(month=Time.now.month, year=Time.now.year)
    BranchOffice.connection.execute "CALL bo_business_days(#{self.id}, #{month}, #{year}, @result)"
    BranchOffice.connection.execute("SELECT @result AS result").fetch_row.first.to_i
  end
  
  # FIXME Add an attribute 'is_default' to branch office
  def self.default
    BranchOffice.first
  end

end
